Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode deleteDuplicates(ListNode head) {
  11. ListNode p = head;
  12. while (p != null) {
  13. while (p.next != null && p.val == p.next.val) {
  14. p.next = p.next.next;
  15. }
  16. p = p.next;
  17. }
  18. return head;
  19. }
  20. }